package com.bbx.androidapi.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.Intent;

public class DataBaseUtil {
	/***
	 * 从asses复制数据库
	 * 
	 * @param context
	 * @param DBPATH
	 *            数据库根目录
	 * @param name
	 *            数据库名
	 * @return 返回 1 = 复制成功 0=文件已经存在 -1=出错
	 */
	public static int copyDBFromAsset(Context context, String DBPATH,
			String name) throws FileNotFoundException, IOException {
		String dbName = name;
		String dbPath = DBPATH + dbName;
		// 判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
		if (!(new File(dbPath).exists())) {
			InputStream is = context.getAssets().open(dbName);// 欲导入的数据库
			File dir = new File(DBPATH);
			dir.mkdir();
			new File(dbPath).createNewFile();
			FileOutputStream fos = new FileOutputStream(dbPath);
			byte[] buffer = new byte[1024];
			int count = 0;
			while ((count = is.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
			}
			fos.close();
			is.close();
			return 1;
		} else {
			return 0;
		}
	}

	/**
	 * 拷贝数据库 如果内置的assets存在就读取 否则联网下载
	 * 
	 * @return
	 */
	public static void copyDBFromNet(Context context, String dbPath,
			String dbName, Intent intent) {
		try {
			copyDBFromAsset(context, dbPath, dbName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			context.startService(intent);
			try {
				File file = new File(dbPath + dbName);
				if (file.exists()) {
					file.delete();
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
}
